﻿using System.Collections.Generic;
using System.Linq;

namespace System.Web.Mvc
{
	public static class EnumerableExtensions
	{
		public static SelectList ToSelectList<T>(this IEnumerable<T> collection)
		{
			return new SelectList(collection, "Key", "Value");
		}

		public static SelectList ToSelectList<T>(this IEnumerable<T> collection, string selectedValue)
		{
			return new SelectList(collection, "Key", "Value", selectedValue);
		}

		public static SelectList ToSelectList<T>(this IEnumerable<T> collection,
							 string dataValueField, string dataTextField)
		{
			return new SelectList(collection, dataValueField, dataTextField);
		}

		public static SelectList ToSelectList<T>(this IEnumerable<T> collection,
							 string dataValueField, string dataTextField, string selectedValue)
		{
			return new SelectList(collection, dataValueField, dataTextField, selectedValue);
		}

		public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector)
		{
			return items.ToSelectList(valueSelector, nameSelector, x => false);
		}

		public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, IEnumerable<TValue> selectedItems)
		{
			return items.ToSelectList(valueSelector, nameSelector, x => selectedItems != null && selectedItems.Contains(valueSelector(x)));
		}

		public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, Func<TItem, bool> selectedValueSelector)
		{
			foreach (var item in items)
			{
				var value = valueSelector(item);

				yield return new SelectListItem
				{
					Text = nameSelector(item),
					Value = value.ToString(),
					Selected = selectedValueSelector(item)
				};
			}
		}
	}
}
